<?php namespace App\Repositories\Eloquent\User;

use App\Models\UserLoginCode;
use App\Repositories\User\UserLoginCodeRepositoryInterface;
use Carbon\Carbon;

class UserLoginCodeRepository implements UserLoginCodeRepositoryInterface
{
    /**
     * 存储用户登陆code
     *
     * @param $user_id
     * @param $code
     * @param $ip
     *
     * @return bool
     */
    public function store($user_id, $code, $expired_at, $ip)
    {
        $model = new UserLoginCode();
        $model->user_id = $user_id;
        $model->code = $code;
        $model->is_used = UserLoginCode::UNUSED;
        $model->expired_at = $expired_at;
        $model->ip = $ip;

        return $model->save();
    }

    /**
     * 获取code对应的有效用户id
     *
     * @param $code
     *
     * @return bool|int
     */
    public function getValidCodeUserId($code)
    {
        $model = UserLoginCode::query()
            ->where('code', $code)
            ->where('is_used', UserLoginCode::UNUSED)
            ->where('expired_at', '>=', Carbon::now()->toDateTimeString())
            ->first();
        if ($model) {
            $model->is_used = UserLoginCode::USED;
            $model->save();

            return (int)$model->user_id;
        }

        return false;
    }
}
